package me.mononin.factory.net;

import android.text.format.DateFormat;
import android.util.Log;

import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;

import java.io.File;
import java.util.Date;

import me.mononin.common.utils.HashUtil;
import me.mononin.factory.Factory;
import me.mononin.factory.persistence.Account;

public class UploadHelper {
    
    private static final String TAG = UploadHelper.class.getSimpleName();
    
    public static final String ENDPOINT = "http://oss-cn-beijing.aliyuncs.com";
    private static final String STS_SERVER = "http://192.168.2.134:7706";
    private static final String BUCKET_NAME = "idlechat";

    /**
     * 获取OSS实例
     *
     * @return
     */
    public static OSS getClient(){
        // 在移动端建议使用STS的方式初始化OSSClient
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(
                "LTAIbrViQL1umE1O", "bCalpvAWOLPQi6WNvykwksP7niy4po");

        /*OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider
                ("LTAIbrViQL1umE1O", "bCalpvAWOLPQi6WNvykwksP7niy4po",
                        "CAISoAN1q6Ft5B2yfSjIpKf3O9DFg7pwxaaBYWv0rEo6QMVGh6Hupzz2IH9KenRgCe4etv41lWtT6/4dlqB6T55OSAmcNZIoAm+QfM7lMeT7oMWQweEuBvTHcDHhg3eZsebWZ+LmNjm0GJOEYEzFkSle2KbzcS7YMXWuLZyOj+xlDLEQRRLqQjdaI91UKwB+yqodLmCDDeuxFRToj2HMbjJvoREupW575Liy5cee5xHC7jj90fRHg4XqPqCtddV3Xud4SMzn9eZxbLbkzSpM6gBD7rtLlKhD8Dul2daGGAt14g6aFODW/9ZzN3VDBM4AFrVDseL3mNBhp+XXjP6X8RtWOvxPWCmtGuLSycDfSuSyLYR7J/Spd17w+fOiCq7TmiYJJjB5RApBYIgmMWQiS05uGH3wF4SE1Wz9RC6GZor9if9mjsIrngy4rIPVfwTUE4/0i3hIZsUOCGozLAMT0GDbdasLThdBaVsPBczOEtstMUAO9/uw51eDDXY9li5NzPT6ZuLLvKcEcpn4XZ9A3ocbaY5Pr2wwVVPzRqJAKMLBisjyKxqAAR448SQMcZXmOWcqlpxpx8ev8l7W36xuTVMuFKqProU/TeMp0rAz0MvAnrph4okoXktpECvuhEJ18u6CCVey+/0SLZRkC7nN3atK/06RHdAUSroAQWQDxvL4iBz0htIB4d5jmm3YcrbZz4WvkhElzE8GeiH9j3SqjUCcM/m32F+h");
*/

        return new OSSClient(Factory.app(),ENDPOINT,credentialProvider);
    }


    /**
     * 文件上传，成功上传后返回一个路径
     *
     * @param objectKey  上传上去后在服务器上独立的key,即为上传路径
     * @param path  文件上传的本地地址
     * @return  上传后返回的文件外网地址
     */
    public static String upload(String objectKey,String path){

        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(BUCKET_NAME, objectKey, path);

        try {
            //初始化上传实例
            OSS oss = getClient();
            //开始同步上传
            PutObjectResult result = oss.putObject(put);
            //得到一个可访问的外网地址
            String url = oss.presignPublicObjectURL(BUCKET_NAME, objectKey);

            Log.d(TAG, String.format("uploadResultUrl:%s ",url));
            return url;
        }catch (Exception e){
            e.printStackTrace();
            Log.d(TAG, e+"");
            return null;
        }
    }


    /**
     * 上传普通图片
     *
     * @param path 本地地址
     * @return 服务器地址
     */
    public static String uploadImage(String path) {
        String key = getImageObjKey(path);
        return upload(key, path);
    }

    /**
     * 上传头像
     *
     * @param path 本地地址
     * @return 服务器地址
     */
    public static String uploadPortrait(String path) {
        String key = getPortraitObjKey(path);
        return upload(key, path);
    }

    /**
     * 上传音频
     *
     * @param path 本地地址
     * @return 服务器地址
     */
    public static String uploadAudio(String path) {
        String key = getAudioObjKey(path);
        return upload(key, path);
    }

    /**
     * 分月存储，避免一个文件夹太多
     *
     * @return yyyyMM
     */
    private static String getDateString() {
        return DateFormat.format("yyyyMM", new Date()).toString();
    }

    // image/201703/test/dawewqfas243rfawr234.jpg
    //test 未测试账户，之后为用户Id
    private static String getImageObjKey(String path) {
        String fileMd5 = HashUtil.getMD5String(new File(path));
        String dateString = getDateString();
        return String.format("image/%s/%s/%s.jpg",Account.getAccount(),dateString, fileMd5);
    }

    // portrait/201703/dawewqfas243rfawr234.jpg
    private static String getPortraitObjKey(String path) {
        String fileMd5 = HashUtil.getMD5String(new File(path));
        String dateString = getDateString();
        return String.format("portrait/%s/%s/%s.jpg",Account.getAccount(),dateString, fileMd5);
    }

    // audio/201703/dawewqfas243rfawr234.mp3
    private static String getAudioObjKey(String path) {
        String fileMd5 = HashUtil.getMD5String(new File(path));
        String dateString = getDateString();
        return String.format("audio/%s/%s/%s.mp3",Account.getAccount(),dateString, fileMd5);
    }

}
